<?php
/**
 * Created by PhpStorm.
 * User: hedonglin
 * Date: 2017/10/26
 * Time: 9:13
 */

namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Dept as DeptModel;
use think\Request;

class Dept extends Controller
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'oes_dept';
    /**
     * 部门页面视图
     * @return mixed
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 级联查询部门
     */
    public function getList(){
        /*$result = Db::table($this->table)->order("sort_code")->select();*/
        $query = "SELECT dept.*,parent.`name` as pname FROM `oes_dept` dept
                  LEFT JOIN oes_dept parent ON dept.parent_id = parent.id ORDER by dept.sort_code";
        $result = Db::query($query);
        return json($result);
    }

    /**
     * 根据id查询部门信息
     * @param $id
     * @return \think\response\Json
     */
    public function getDeptById($id){
        //查询出上级部门的部门name
        $query = "SELECT dept.*,parent.`name` as pname FROM `oes_dept` dept
                    LEFT JOIN oes_dept parent ON dept.parent_id = parent.id
                    WHERE dept.id = ?";
        $result = DB::query($query, [$id]);
        return json($result);
    }

    /**
     * 新增部门
     * @param Request $request
     * @return \think\response\Json
     */
    public function addDept(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['name', 'sort_code', 'parent_id','status']);
        if ($data['parent_id']==null){
            $data = $request->only(['name', 'sort_code','status']);
        }
        // 添加数据
        $result = DeptModel::create($data);
        // 返回数据
        if ($result) {
            return json(['success'=>true, "msg"=>'添加成功']);
        } else {
            return json(['success'=>false, "msg"=>'添加失败']);
        }
    }

    /**
     * 修改部门
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateDept(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(["id",'name','sort_code','parent_id','status']);
        if ($data['parent_id']==null){
            $data = $request->only(["id",'name', 'sort_code','status']);
        }
        // 添加数据
        $result = DeptModel::update($data);
        // 返回数据
        if ($result) {
            return json(['success'=>true, "msg"=>'修改成功']);
        } else {
            return json(['success'=>false, "msg"=>'修改失败']);
        }
    }

    /**
     * 逻辑删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function deleteDept(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(["id",'status']);
        // 添加数据
        $result = DeptModel::update($data);
        // 返回数据
        if ($result) {
            return json(['success'=>true, "msg"=>'删除成功']);
        } else {
            return json(['success'=>false, "msg"=>'删除失败']);
        }
    }


}